package org.ykhl.handlers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncTask;
import org.springframework.web.servlet.ModelAndView;
import org.ykhl.handlers.dao.LongTimeAsyncCallService;
import org.ykhl.handlers.util.RequestCache;

import java.util.concurrent.Callable;

/**
 * Created by wcd on 2017/3/15.
 */
@RestController
public class RequestHandler {
    @Autowired
    LongTimeAsyncCallService longTimeAsyncCallService;
    @RequestMapping(value="/asynctask",method = RequestMethod.GET)
    public DeferredResult<ModelAndView> asyncTask(){
        final DeferredResult<ModelAndView> deferredResult = new DeferredResult<ModelAndView>();
        System.out.println("/asynctask 调用！thread id is : "+Thread.currentThread().getId());
        RequestCache.putCache("test",deferredResult);
        longTimeAsyncCallService.runexecute();
        deferredResult.onTimeout(new Runnable() {
            public void run() {
                System.out.println("异步调用执行超时！thread id is : " + Thread.currentThread().getId());
                ModelAndView mav = new ModelAndView("remotecalltask");
                mav.addObject("result", "异步调用执行超时");
                deferredResult.setResult(mav);
            }
        });
        System.out.println("调用ok");
        return deferredResult;
    }

    @RequestMapping(value="/longtimetask",method = RequestMethod.GET)
    public WebAsyncTask longTimeTask(){
        System.out.println("/longtimetask被调用 thread id is : " + Thread.currentThread().getId());
        Callable<ModelAndView> callable =new Callable<ModelAndView>() {
            public ModelAndView call() throws Exception {
                Thread.sleep(3000);//假设是一些长时间任务
                ModelAndView mav =new ModelAndView("longtimetask");
                mav.addObject("result","执行成功");
                System.out.println("执行成功 thread id is : " + Thread.currentThread().getId());

                return mav;
            }
        };
        System.out.println("方法底部");

        WebAsyncTask asyncTask =new WebAsyncTask(2000,callable);
        asyncTask.onTimeout(new Callable<ModelAndView>() {
            public ModelAndView call() throws Exception {
                ModelAndView mav =new ModelAndView("longtimetask");
                mav.addObject("result","执行超时");
                System.out.println("执行超时 thread id is : " + Thread.currentThread().getId());
                return mav;
            }
        });
        return new WebAsyncTask(3000,callable);
    }
}
